import { Module } from 'vuex'
import { ILoginState } from './type'
import { IRootState } from '@/store/type'
import { $select } from '@/service/common'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      agentCodeArr: []
    }
  },
  mutations: {
    changeAgentCodeArr(state, arr: any) {
      state.agentCodeArr = arr
    }
  },
  actions: {
    async getAgentCodeArr({ commit }) {
      const result = localStorage.getItem('agentCodeArr') ?? ''
      const token = localStorage.getItem('token')
      if (!result && token) {
        const { data } = await $select.select()
        localStorage.setItem('agentCodeArr', JSON.stringify(data))
        return commit('changeAgentCodeArr', data)
      }
      result && commit('changeAgentCodeArr', JSON.parse(result))
    }
  },
  getters: {
    agentCodes(state) {
      return state.agentCodeArr.map((item) => {
        item.title = item.name
        item.value = item.agentCode
        return item
      })
    }
  }
}

export default loginModule
